import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../lib_network/http_helper.dart';
import 'me_api.dart';

/// 内购封装服务（单例模式）
class InAppPurchaseService {
  // 单例实例
  static final InAppPurchaseService _instance =
      InAppPurchaseService._internal();
  factory InAppPurchaseService() => _instance;

  InAppPurchaseService._internal() {
    // 订阅内购更新，监听购买状态
    _purchaseUpdatedSubscription = InAppPurchase.instance.purchaseStream.listen(
      _listenToPurchaseUpdated,
      onDone: () => _purchaseUpdatedSubscription.cancel(),
      onError: (error) {
        // 这里可以添加统一错误处理
        debugPrint('Purchase stream error: $error');
      },
    );
  }

  late StreamSubscription<List<PurchaseDetails>> _purchaseUpdatedSubscription;

  /// 内购更新监听器
  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    for (final purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.canceled) {
        print('购买status 取消:');
      }
      // 购买处理中
      if (purchaseDetails.status == PurchaseStatus.pending) {
        print('购买处理中：${purchaseDetails.productID}');
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          // 处理购买错误
          print('购买错误：${purchaseDetails.error}');
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          // 进行购买校验，并交付商品
          _handlePurchase(purchaseDetails);
        }
        // 完成购买流程（对于部分平台要求调用 completePurchase）
        if (purchaseDetails.pendingCompletePurchase) {
          InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    }
  }

  /// 对购买结果进行校验和处理（可选：建议对接服务器验证）
  Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
    bool valid = await _verifyPurchase(purchaseDetails);
    if (valid) {
      // 校验成功，交付商品
      print('购买成功，交付商品：${purchaseDetails.productID}');
      // TODO: 在这里触发业务逻辑，比如调用后端接口更新购买状态等
    } else {
      // 校验失败，进行错误提示或回滚
      print('购买校验失败：${purchaseDetails.productID}');
    }
  }

  /// 模拟验证购买（建议接入自己的服务器进行验证）
  Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    if (Platform.isIOS) {
      // 此处可以调用接口传送 purchaseDetails.verificationData 给后端校验
      String? purchaseToken =
          purchaseDetails.verificationData.serverVerificationData;
      var res = await HttpHelper.instance().post(
        MeApi.applePurchase,
        // body: {
        //   // "packageName": "com.habi.gameplay",
        //   "productId": purchaseDetails.productID,
        //   "purchaseToken": purchaseToken
        // },
        showLoading: true,
        showToast: true,
      );
      return Future.value(res.isSuccess);
    } else if (Platform.isAndroid) {
      //android相关代码

      // 此处可以调用接口传送 purchaseDetails.verificationData 给后端校验
      String? purchaseToken =
          purchaseDetails.verificationData.serverVerificationData;
      var res = await HttpHelper.instance().post(
        MeApi.verifyPurchase,
        body: {
          "packageName": "com.habi.gameplay",
          "productId": purchaseDetails.productID,
          "purchaseToken": purchaseToken
        },
        showLoading: true,
        showToast: true,
      );
      return Future.value(res.isSuccess);
    } else {
      return Future.value(false);
    }
  }

  /// 根据商品 id 发起支付（消费型）
  /// 如果是非消耗型，请替换为 buyNonConsumable 方法
  Future<void> purchaseProduct(String productId) async {
    // 检查商店是否可用
    final bool available = await InAppPurchase.instance.isAvailable();
    if (!available) {
      debugPrint('内购服务不可用');
      return;
    }

    // 查询商品详情
    final Set<String> productIds = {productId};
    final ProductDetailsResponse response =
        await InAppPurchase.instance.queryProductDetails(productIds);
    if (response.notFoundIDs.isNotEmpty) {
      // 商品id无效或未在商店中配置
      debugPrint('未找到商品：${response.notFoundIDs}');
      return;
    }
    if (response.productDetails.isEmpty) {
      debugPrint('查询结果为空');
      return;
    }
    final ProductDetails productDetails = response.productDetails.first;

    // 构造购买参数
    final PurchaseParam purchaseParam =
        PurchaseParam(productDetails: productDetails);

    try {
      print('发起购买');
      // 发起购买：这里以消费型商品为例，非消耗型使用buyNonConsumable
      await InAppPurchase.instance.buyConsumable(
        purchaseParam: purchaseParam,
        autoConsume: true, // 如果需要手动消耗则改为 false，并在购买成功后调用 consumePurchase
      );
    } catch (e) {
      print('发起购买异常：$e');
    }
  }

  /// 释放资源
  void dispose() {
    _purchaseUpdatedSubscription.cancel();
  }
}
